package com.hotec.PROJECT_NAME.modules.sys.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hotec.PROJECT_NAME.component.basic.BaseService;
import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import com.hotec.PROJECT_NAME.modules.sys.entity.SysDict;
import com.hotec.PROJECT_NAME.modules.sys.mapper.SysDictMapper;
import com.hotec.PROJECT_NAME.utils.UtilsLog;
import com.hotec.PROJECT_NAME.utils.UtilsTreeBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author llb
 * @date
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysDictService extends BaseService<SysDict, SysDictMapper> {
    public List<SysDict> queryChildrenList(String parentCode) {
        if (StrUtil.isEmpty(parentCode)) {
            return Lists.newArrayList();
        }
        SysDict parentDictCond = new SysDict();
        parentDictCond.setCode(parentCode.trim());
        PageHelper.orderBy("sort_ asc");
        List<SysDict> parentDictList = this.mapper.select(parentDictCond);
        if (parentDictList == null || parentDictList.size() < 1) {
            return Lists.newArrayList();
        }

        String parentId = parentDictList.get(0).getId();

        SysDict childDictCond = new SysDict();
        childDictCond.setParentId(parentId);
        PageHelper.orderBy("sort_ asc");
        List<SysDict> childrenSysDictS = mapper.select(childDictCond);
        //结果排序
//        if( childrenSysDictS!=null ){
//            Collections.sort( childrenSysDictS ) ;
//        }

        return childrenSysDictS;
    }

    /**
     * 查询子字典项列表
     *
     * @param parentCode
     * @return 返回所有子节点code和name的映射
     */
    public Map<String, String> queryChildrenMap(String parentCode) {
        List<SysDict> sysDictVOS = queryChildrenList(parentCode);
        if (sysDictVOS == null || sysDictVOS.size() < 1) {
            return Maps.newLinkedHashMap();
        }
        Map<String, String> itemMaps = Maps.newLinkedHashMap();

        for (SysDict sysDictVO : sysDictVOS) {
            itemMaps.put(sysDictVO.getCode(), sysDictVO.getName());
        }

        return itemMaps;
    }
    public List<SysDict> queryChildren(String parentCode) {
        List<SysDict> sysDictVOS = queryChildrenList(parentCode);


        return sysDictVOS;
    }


    @Override
    public List queryAll(SysDict entity) {
        Example example = new Example(SysDict.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(entity.getCode())) {
            criteria.andCondition("code like '%" + entity.getCode().trim().replaceAll("[%_$]", "/$0") + "%'  ");
        }
        if (StringUtils.isNotBlank(entity.getName())) {
            criteria.andCondition("name like '%" + entity.getName().trim().replaceAll("[%_$]", "/$0") + "%'  ");
        }

        example.createCriteria().andLike("parentPath", "%" + entity.getParentPath() + "%").andEqualTo("delFlag", "0");

        criteria.andNotEqualTo("id", "0");
        List list = super.queryByExample(1, 1000, "sort_ asc,create_time desc", example).getList();
        if (CollectionUtils.isNotEmpty(list)) {
            return new UtilsTreeBuilder(SysDict.class).listToTree(list);
        }
        return Lists.newArrayList();
    }

    public List<SysDict> queryAllWithOutTree(SysDict sysDict) {
        SysDict one = this.getOne(new SysDict().setCode(sysDict.getCode()));
        //遍历我所有的角色，查询所有角色的下级
        Example example = new Example(SysDict.class);
        example.createCriteria().andLike("parentPath", "%" + one.getParentPath() + "%").andEqualTo("delFlag", "0").andNotEqualTo("id", "0").andNotEqualTo("parentId", "0");
        List<SysDict> all = this.mapper.selectByExample(example);

        Collections.sort(all, new Comparator<SysDict>() {
            @Override
            public int compare(SysDict o1, SysDict o2) {
                int mark = 1;
                try {
                    Date date0 = o1.getCreateTime();
                    Date date1 = o2.getCreateTime();
                    if (date0.getTime() < date1.getTime()) {
                        mark = -1;
                    }
                    if (date0.equals(date1)) {
                        mark = 0;
                    }
                } catch (Exception e) {
                    UtilsLog.log(this.getClass(), e);
                }
                return mark;
            }

        });

        return all;
    }

    public List<SysDict> queryAllWithOutTreeByCode(SysDict sysDict) {
        SysDict one = this.getOne(new SysDict().setCode(sysDict.getCode()));
        //遍历我所有的角色，查询所有角色的下级
        Example example = new Example(SysDict.class);
        example.createCriteria().andLike("parentPath", "%" + one.getParentPath() + "%").andEqualTo("delFlag", "0").andNotEqualTo("id", "0");
        return this.mapper.selectByExample(example);
    }


    public List<SysDict> queryTreeByCode(SysDict sysDict) {
        List list = new UtilsTreeBuilder(SysDict.class).listToTree(this.queryAllWithOutTreeByCode(sysDict).stream().distinct().collect(Collectors.toList()));
        return list;
    }


    @Override
    public SysDict save(SysDict dict) {
        SysDict sysDictVO = new SysDict();
        sysDictVO.setParentId(dict.getParentId());
        sysDictVO.setCode(dict.getCode());
        sysDictVO.setDelFlag("0");
        List<SysDict> select = mapper.select(sysDictVO);
        //新增
        if (StrUtil.isBlank(dict.getId())) {
            if (select != null && select.size() > 0) {
                throw new BizException("字典值[" + sysDictVO.getCode() + "]在同一父类下面已经存在!");
            }
        } else {
            SysDict old = mapper.selectByPrimaryKey(dict.getId());
            if (!StrUtil.equalsIgnoreCase(old.getCode(), dict.getCode())) {
                if (select != null && select.size() > 0) {
                    throw new BizException("字典值[" + sysDictVO.getCode() + "]在同一父类下面已经存在!");
                }
            }
        }
        return super.save(dict);
    }

    public List<SysDict> queryTree(SysDict sysDict) {
        List<SysDict> list = new UtilsTreeBuilder<>(SysDict.class).listToTree(this.queryAllWithOutTree(sysDict).stream().distinct().collect(Collectors.toList()));
        transFormChildren(list);
        return list;
    }

    public void transFormChildren(List<SysDict> list) {
        if (list.size() == 0) {
            list = null;
            return;
        }
        list.forEach(item -> {
            if (item.getChildren() != null && item.getChildren().size() > 0) {
                transFormChildren(item.getChildren());
            } else {
                item.setChildren(null);
            }
        });
    }


    public List<SysDict> queryChildByParentCode(String parentCode) {
        if(StrUtil.isBlank(parentCode)) return Lists.newArrayList();

        SysDict parentDict = getOne(new SysDict().setCode(parentCode));

        Example example = Example.builder(SysDict.class)
                .select("id", "name", "code", "remark")
                .andWhere(
                        Sqls.custom()
                                .andEqualTo("parentId", parentDict.getId())
                                .andEqualTo("delFlag", "0")
                )
                .orderByAsc("sort")
                .build();

        return mapper.selectByExample(example);
    }
}
